package com.wuxiaoqin.server.service.impl;


import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.payment.page.models.AlipayTradePagePayResponse;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.wuxiaoqin.server.config.AliPayConfig;
import com.wuxiaoqin.server.entity.Orders;
import com.wuxiaoqin.server.entity.Users;
import com.wuxiaoqin.server.mapper.OrdersMapper;
import com.wuxiaoqin.server.mapper.UsersMapper;
import com.wuxiaoqin.server.service.IUsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@Service
public class AlipayService {
    @Autowired
    private AliPayConfig alipayConfig;

    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private UsersMapper usersMapper;
    /**
     * 电脑版支付
     *
     * @param subject 标题
     * @param orderId 订单ID
     * @param uId
     * @return
     * @throws Exception
     */
    public String toPayPage(String subject, Integer orderId, Integer uId) throws Exception {

        Orders orders = ordersMapper.selectById(orderId);
        if (!uId.equals(orders.getUId())){
            return "用户订单异常，重新审核之后在支付";
        }
        if (orders == null||!orders.getOrderno().equals(orderId)||orders.getStatus()>0){
            return "订单异常，重新审核之后在支付";
        }
        String orderNumber = orderId.toString();
        BigDecimal payment = orders.getPayment();
        String total = payment.toString();
        AlipayTradePagePayResponse response1 = Factory.Payment.Page().pay(subject, orderNumber, total, alipayConfig.return_url);
        return response1.getBody();
    }


    public String notifyService(HttpServletRequest request) throws Exception {
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            System.out.println("=========支付宝异步回调========");


            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
                 System.out.println(name + " = " + request.getParameter(name));
            }
            System.out.println(Factory.Payment.Common().verifyNotify(params)+"======================renzheng");
            // 支付宝验签
            //if (Factory.Payment.Common().verifyNotify(params)) {
                // 验签通过
                System.out.println("交易名称: " + params.get("subject"));
                System.out.println("交易状态: " + params.get("trade_status"));
                System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
                System.out.println("商户订单号: " + params.get("out_trade_no"));
                System.out.println("交易金额: " + params.get("total_amount"));
                System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));
                System.out.println("买家付款时间: " + params.get("gmt_payment"));
                System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));
                int out_trade_no = Integer.parseInt(params.get("out_trade_no"));

                Orders orders = ordersMapper.selectById(out_trade_no);
                orders.setStatus(1);
                orders.setStatusdesc("已支付");
                orders.setPaymenttime(params.get("gmt_payment"));
                ordersMapper.updateById(orders);

                //增加积分(未测试)
            BigDecimal divide = orders.getPayment().divide(new BigDecimal(100));
            int point = divide.setScale(0, BigDecimal.ROUND_DOWN).intValue();
            usersMapper.update(null, new UpdateWrapper<Users>().set("U_points", point).eq("U_id", orders.getUId()));
            //}
        }
        return "success";

    }


}
